// 数据库管理类
export class ImageFeatureDB {
    constructor() {
        this.db = null;
        this.DB_NAME = 'MultiAlgorithmImageDB';
        this.DB_VERSION = 3;
        this.STORE_NAME = 'imageFeatures';
    }

    async init() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);

            request.onerror = () => reject(request.error);
            request.onsuccess = () => {
                this.db = request.result;
                resolve(this.db);
            };

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                if (!db.objectStoreNames.contains(this.STORE_NAME)) {
                    const store = db.createObjectStore(this.STORE_NAME, { keyPath: 'name' });
                    store.createIndex('timestamp', 'timestamp', { unique: false });
                }
            };
        });
    }

    async storeImageFeatures(imageName, features, thumbnail) {
        console.log('开始处理图片:', imageName)
        const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
        console.log('开始处理图片:', features)
        const store = transaction.objectStore(this.STORE_NAME);
        console.log('开始处理图片:', thumbnail)
        return store.put({
            name: imageName,
            features: features,
            thumbnail: thumbnail,
            timestamp: Date.now()
        });
    }

    async getAllImages() {
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
            const store = transaction.objectStore(this.STORE_NAME);
            const request = store.getAll();

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async clearDatabase() {
        const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
        const store = transaction.objectStore(this.STORE_NAME);
        return store.clear();
    }

    async getImageCount() {
        const images = await this.getAllImages();
        return images.length;
    }
}